<template>
  <div class="index">
    <a-form
      ref="formRef"
      :model="form"
      auto-label-width
      :style="{ width: '600px' }"
      :rules="rules"
    >
      <a-form-item field="flowName" label="流程名">
        <a-input v-model="form.flowName" @change="checkUnique" />
      </a-form-item>
      <!-- <a-form-item field="flowCode" label="流程编号">
        <a-input v-model="form.flowCode" />
      </a-form-item> -->

      <a-form-item field="icon" label="流程图标">
        <a-input v-model="form.icon" />
      </a-form-item>
      <a-form-item field="illustrate" label="流程说明">
        <a-input v-model="form.illustrate" />
      </a-form-item>
      <a-form-item field="businessAcronyms" label="适用业务">
        <a-select v-model="form.businessAcronyms">
          <a-option
            v-for="item in applicableBusinessList"
            :key="item.id"
            :value="item.businessAcronyms"
            >{{ item.businessName }}</a-option
          >
        </a-select>
      </a-form-item>
      <!-- <a-form-item field="businessAcronyms" label="业务缩略词">
        <a-input v-model="form.businessAcronyms" />
      </a-form-item>
      <a-form-item field="businessName" label="适用业务名称">
        <a-input v-model="form.businessName" />
      </a-form-item> -->
      <!-- <a-form-item field="addSignature" label="是否开启加签操作">
        <a-switch
          :checked-value="1"
          :unchecked-value="2"
          v-model="form.addSignature"
        >
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch>
      </a-form-item>
      <a-form-item field="automaticWeightRemoval" label="是否开启自动去重">
        <a-switch
          :checked-value="1"
          :unchecked-value="2"
          v-model="form.automaticWeightRemoval"
        >
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch>
      </a-form-item>
      <a-form-item field="timeLimitedApproval" label="是否开启限时审批">
        <a-switch
          :checked-value="1"
          :unchecked-value="2"
          v-model="form.timeLimitedApproval"
        >
          <template #checked> 开启 </template>
          <template #unchecked> 关闭 </template>
        </a-switch>
      </a-form-item> -->
      <a-form-item field="participantInfoList" label="可见性范围">
        <div
          style="
            border: 1px solid #c9cdd4;
            width: 100%;
            border-radius: 4px;
            display: flex;
            flex-wrap: wrap;
            min-height: 30px;
            cursor: text;
          "
          @click="tagClick"
        >
          <a-tag style="margin: 5px">test</a-tag>
          <a-tag
            v-for="tag in form.participantInfoList"
            :key="tag.objId"
            closable
            style="margin: 5px"
            @close="delTag(tag.id)"
            >{{ tag.objName }}</a-tag
          >
        </div>
      </a-form-item>
      <!-- <a-form-item field="formSource" label="流程表单来源">
            <a-input-number v-model="form.formSource" />
          </a-form-item> -->
      <!-- <a-form-item field="subsidiaryFormId" label="流程附属表单">
            <a-input-number v-model="form.subsidiaryFormId" />
          </a-form-item> -->
      <a-space direction="vertical" fill style="align-items: center">
        <a-button @click="saveFlow" :type="'primary'" style="width: 200px">
          保存信息
        </a-button>
      </a-space>
    </a-form>
    <HumanMadal
      v-model:visible="rorleVisible"
      v-model:data="currenHuman"
      @submit="roleOk"
    />
  </div>
</template>
<script setup lang="ts">
import type { Flow, ApplicableBusiness } from '@/apis/flow/type';
import * as apiFlow from '@/apis/flow/index';
import { getFlowById } from '@/apis/flow/index';
import { useRoute } from 'vue-router';
import router from '@/router';
import HumanMadal from '../Flow/componnents/HumanMadal/index.vue';
import cloneDeep from 'lodash.clonedeep';
import { delFlowParticipantByIds } from '@/apis/flowPanelPoint';
import { Message, Notification } from '@arco-design/web-vue';
import { useVModel } from '@vueuse/core';
import { getApplicableBusiness } from '@/apis/applicableBusiness/index';

const props = withDefaults(
  //参数说明
  defineProps<{
    /**
     * 流程基础信息
     */
    data: Flow;
  }>(),
  {
    data: () => ({})
  }
);
const emits = defineEmits(['update:data', 'save']);
const form = useVModel(props, 'data', emits);
const route = useRoute();
const rorleVisible = ref(false);
const currenHuman = ref<any[]>([]);
const tagClick = () => {
  currenHuman.value = cloneDeep(form.value.participantInfoList) || [];

  rorleVisible.value = true;
};
//新旧数据对比，找到删掉的人员和新增的人员
const delIds = ref<number[]>([]);
const addData = ref<any>([]);
const roleOk = () => {
  let arr: any = [];

  currenHuman.value.forEach((human) => {
    const { id, name, type } = human;
    arr.push({
      objId: id,
      objName: name,
      objType: type
    });
    const index = form.value.participantInfoList?.findIndex(
      (participant) =>
        participant.objId === id || (participant.objType === type && type === 5)
    );
    if (typeof index !== 'number' || Number(index) < 0) {
      let obj = {
        objId: id,
        objName: name,
        objType: type
      };
      const n = addData.value.findIndex((ele) => ele.objId === id);
      if (n < 0) {
        addData.value.push(obj);
      }
    }
  });
  form.value.participantInfoList?.forEach((participant) => {
    const index = currenHuman.value.findIndex(
      (human) =>
        participant.objId === human.id ||
        (participant.objType === human.type && human.type === 5)
    );
    if (typeof index !== 'number' || Number(index) < 0) {
      if (!delIds.value.includes(participant.id)) {
        delIds.value.push(participant.id);
      }
    }
  });

  form.value.participantInfoList = arr;
  rorleVisible.value = false;
};
const saveFlow = async () => {
  if (delIds.value.length) {
    await delFlowParticipantByIds({ ids: delIds.value });
  }

  let copyForm = cloneDeep(form.value);
  copyForm.participantInfoList = addData.value;
  if (!copyForm.id) {
    const res = await apiFlow.AddFlow(copyForm);
    if (res?.processId) {
      router.replace({
        path: '/process/setting',
        query: { id: res.processId }
      });
    }
  } else {
    await apiFlow.editFlow(copyForm);
  }
  delIds.value.length = 0;
  addData.value.length = 0;
  Notification.info('保存成功');
};
const delTag = async (data: any) => {
  await delFlowParticipantByIds({ ids: [data] });
};

const init = () => {
  getApplicableBusinessList();
};
const applicableBusinessList = ref<ApplicableBusiness[]>([]);
const getApplicableBusinessList = async () => {
  const res = await getApplicableBusiness();
  applicableBusinessList.value = res.list || [];
};
onMounted(() => {
  init();
});
const formRef = ref();
const rules = {
  flowName: [
    {
      required: true,
      trigger: "['change', 'input', 'blur']",
      message: '名称不能为空'
    }
  ]
};
const checkUnique = async () => {
  const res = await apiFlow.flowDuplicateCheck({
    flowName: `${form.value.flowName}`
  });
  if (res?.code === 400) {
    formRef.value.setFields({
      flowName: { status: 'error', message: res.msg }
    });
  }
};
</script>
<style lang="less" scoped>
.index {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 64px 0;
}
.btn {
  position: absolute;
  top: 14px;
  right: 16px;
}
</style>
